package com.zhny.project.txt.dataset.controller;

import com.zhny.common.utils.file.FileUploadUtils;
import com.zhny.common.utils.poi.ExcelUtil;
import com.zhny.framework.aspectj.lang.annotation.Log;
import com.zhny.framework.aspectj.lang.enums.BusinessType;
import com.zhny.framework.config.RuoYiConfig;
import com.zhny.framework.web.controller.BaseController;
import com.zhny.framework.web.domain.AjaxResult;
import com.zhny.framework.web.page.TableDataInfo;
import com.zhny.project.txt.dataset.domain.TxtDataset;
import com.zhny.project.txt.dataset.mapper.TxtDatasetMapper;
import com.zhny.project.txt.dataset.service.ITxtDatasetService;
import com.zhny.project.txt.indexset.service.ITxtIndexsetService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TXT数据集Controller
 *
 * @author yanqun
 * @date 2019-12-09
 */
@Controller
@RequestMapping("/txt/dataset")
public class TxtDatasetController extends BaseController
{
    private String prefix = "txt/dataset";

    @Autowired
    private ITxtDatasetService txtDatasetService;
    @Autowired
    private ITxtIndexsetService txtIndexsetService;
    @Autowired
    private TxtDatasetMapper txtDatasetMapper;

    @RequiresPermissions("txt:dataset:view")
    @GetMapping()
    public String dataset()
    {
        return prefix + "/dataset";
    }

    /**
     * 查询TXT数据集列表
     */
    @RequiresPermissions("txt:dataset:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TxtDataset txtDataset)
    {
        startPage();
        List<TxtDataset> list = txtDatasetService.selectTxtDatasetList(txtDataset);
        return getDataTable(list);
    }

    /**
     * 导出TXT数据集列表
     */
    @RequiresPermissions("txt:dataset:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TxtDataset txtDataset)
    {
        List<TxtDataset> list = txtDatasetService.selectTxtDatasetList(txtDataset);
        ExcelUtil<TxtDataset> util = new ExcelUtil<TxtDataset>(TxtDataset.class);
        return util.exportExcel(list, "dataset");
    }

    /**
     * 新增TXT数据集
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存TXT数据集
     */
    @RequiresPermissions("txt:dataset:add")
    @Log(title = "TXT数据集", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TxtDataset txtDataset, MultipartFile  multipartFile)
            throws IOException {
        StringBuilder result = new StringBuilder();
        int flag = 0;
        try
        {
            //存放本地
            String filepath = RuoYiConfig.getProfile();
            String files = FileUploadUtils.upload(filepath, multipartFile);
            File uploadFile = new File(files);

            String filePath = files;
            FileInputStream fin = new FileInputStream(filePath);
            InputStreamReader reader = new InputStreamReader(fin);
            BufferedReader buffReader = new BufferedReader(reader);
            String strTmp = "";
            int row = 0;
            //surface 处理完字段名
            //lis：未处理字段名
            List<String> surface=new ArrayList<String>();
            List<String> lis=new ArrayList<String>();

            //创建数据集
            String deta = txtDatasetService.insertTxtDataset(txtDataset);

            //循环创建数据表插入数据表
            while((strTmp = buffReader.readLine())!=null){
              int rows =  row + 1;
                if (rows == 1){
                    //创建数据表
                    lis.add(strTmp);
                 String string = txtDatasetService.addsurface(strTmp,txtDataset);
                    surface.add(string);
                }
               if (rows > 1){
                   //向数据表中添加数据
                   txtDatasetService.insertTxtinto(strTmp,txtDataset,surface,deta);
               }
                row++;
            }
            //创建指标集
           int list = txtIndexsetService.insertTxtinto(txtDataset,deta,lis,surface);

        }catch (Exception e)
        {
                 System.err.println(e);
        }
        return toAjax(1);
    }




    //csv文件
    @RequiresPermissions("txt:dataset:add")
    @Log(title = "TXT数据集", businessType = BusinessType.INSERT)
    @PostMapping("/csv")
    @ResponseBody
    public AjaxResult csv(TxtDataset txtDataset, MultipartFile  multipartFile)
            throws IOException{
        List<String> dataList = new ArrayList<String>();
        List<String> string = new ArrayList<String>();
        List<String> surface = new ArrayList<String>();
        BufferedReader bufferedReader = null;
        try
        {
            //存放本地
            String filepath = RuoYiConfig.getProfile();
            String files = FileUploadUtils.upload(filepath, multipartFile);
            File uploadFile = new File(files);
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(files), "utf-8"));//GBK


            String filePath = reader.toString();
            String line = "";
            int mun = 0;
            String deta = txtDatasetService.insertTxtDataset(txtDataset);
            while ((line = reader.readLine())!=null){
                mun++;
                if (mun==1){
                    string.add(line);
                    String index = txtDatasetService.csvsurface(line,txtDataset);
                    surface.add(index);
                    System.out.print(mun);
                }
                if (mun>1){
                    txtDatasetService.csvTxtinto(line,txtDataset,surface,deta);
                    dataList.add(line);
                }
            }
            int list = txtIndexsetService.csvTxtinto(txtDataset,deta,string,surface);
        }catch (Exception e)
        {
            System.err.println(e);
        }
        return toAjax(1);
    }




    /**
     * 修改TXT数据集
     */
    @GetMapping("/edit/{datasetKey}")
    public String edit(@PathVariable("datasetKey") String datasetKey, ModelMap mmap)
    {
        TxtDataset txtDataset = txtDatasetService.selectTxtDatasetById(datasetKey);
        mmap.put("txtDataset", txtDataset);
        return prefix + "/edit";
    }

    /**
     * 修改保存TXT数据集
     */
    @RequiresPermissions("txt:dataset:edit")
    @Log(title = "TXT数据集", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TxtDataset txtDataset)
    {
        return toAjax(txtDatasetService.updateTxtDataset(txtDataset));
    }

    /**
     * 删除TXT数据集
     */
    @RequiresPermissions("txt:dataset:remove")
    @Log(title = "TXT数据集", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(txtDatasetService.deleteTxtDatasetById(ids));
    }



    @GetMapping("/txtTemplate/{resource}")
    public void resourceDownload(@PathVariable("resource")String resource,  HttpServletRequest request, HttpServletResponse response)
                throws Exception
    {
//        方法二
            String fileName = "txtTemplate.txt";
            String allPathName = RuoYiConfig.getTxtDownload() +  "txtTemplate.txt";
            response.setHeader("content-disposition", "attachment;filename="+fileName);
            InputStream in=null;
            OutputStream out=null;
            try {
                in=new FileInputStream(allPathName);
                int len = 0;
                byte[] buffer = new byte[1024];
                out = response.getOutputStream();
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer,0,len);
                }
            }catch (FileNotFoundException e){
                e.printStackTrace();
            }finally{
                in.close();
                out.close();
            }

    }

    //判断数据集有没有被做过特征值
    @PostMapping("/checkSpValue")
    @ResponseBody
    public Map<String,Object> checkSpValue(String key){
        Map<String,Object> map = new HashMap<String,Object>();
        int flag = 0;
        TxtDataset infor = txtDatasetMapper.selectDisposeIcon(key);
        //infor.getDisposeIcon()= 4 已经做过特征值
        if(("4").equals(infor.getDisposeIcon()) ){
            flag =  4;
        //infor.getDisposeIcon()=2 || 3 做过质量值  ，没做过特征值
        }else if(("2").equals(infor.getDisposeIcon()) || ("3").equals(infor.getDisposeIcon())){
            flag = 2;
           // infor.getDisposeIcon() = 1 没做过质量值
        }else{
            flag = 1;
        }
        map.put("flag",flag);
        return  map;
    }
}
